import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { get, patch, put } from '../utils/api'

export const useNotificationStore = defineStore('notification', () =>
{
  // 状态
  const notifications = ref([])
  const unreadNotifications = ref([])
  const unreadCount = ref(0)
  const loading = ref(false)

  // 开源版本检测
  const isOpenSourceVersion = ref(true) // 开源版本默认为true

  // 计算属性
  const hasUnreadNotifications = computed(() => unreadCount.value > 0)

  // 获取通知统计
  const fetchNotificationStats = async () =>
  {
    try
    {
      console.log('📊 开始获取通知统计...')

      // 开源版本跳过通知API调用
      if (isOpenSourceVersion.value)
      {
        console.log('📊 开源版本跳过通知统计API调用')
        unreadCount.value = 0
        unreadNotifications.value = []
        return { success: true, message: '开源版本暂不支持通知功能' }
      }

      const response = await get('/notifications/stats')
      console.log('📊 通知统计API响应:', response)

      if (response.code === 200)
      {
        const stats = response.data
        unreadCount.value = stats.unreadCount
        if (stats.recentNotifications)
        {
          unreadNotifications.value = stats.recentNotifications
        }
        console.log('📊 通知统计更新成功:', {
          unreadCount: unreadCount.value,
          recentNotifications: unreadNotifications.value
        })
        return { success: true, data: stats }
      } else
      {
        throw new Error(response.message || '获取通知统计失败')
      }
    } catch (error)
    {
      console.error('📊 获取通知统计失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 获取通知列表
  const fetchNotifications = async (page = 0, size = 20) =>
  {
    try
    {
      // 开源版本跳过
      if (isOpenSourceVersion.value)
      {
        console.log('📊 开源版本跳过通知列表API调用')
        notifications.value = []
        return { success: true, data: { content: [], totalElements: 0 } }
      }

      loading.value = true
      const response = await get('/notifications', { page, size })

      if (response.code === 200)
      {
        notifications.value = response.data.content || []
        return { success: true, data: response.data }
      } else
      {
        throw new Error(response.message || '获取通知列表失败')
      }
    } catch (error)
    {
      console.error('获取通知列表失败:', error)
      ElMessage.error('获取通知失败: ' + error.message)
      return { success: false, message: error.message }
    } finally
    {
      loading.value = false
    }
  }

  // 获取未读通知
  const fetchUnreadNotifications = async () =>
  {
    try
    {
      const response = await get('/notifications/unread')
      if (response.code === 200)
      {
        unreadNotifications.value = response.data || []
        unreadCount.value = response.data.length
        return { success: true, data: response.data }
      } else
      {
        throw new Error(response.message || '获取未读通知失败')
      }
    } catch (error)
    {
      console.error('获取未读通知失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 标记通知为已读
  const markNotificationAsRead = async (notificationId) =>
  {
    try
    {
      const response = await patch(`/notifications/${notificationId}/read`)
      if (response.code === 200)
      {
        // 更新本地状态
        const notification = notifications.value.find(n => n.id === notificationId)
        if (notification)
        {
          notification.status = 'READ'
          notification.readAt = new Date().toISOString()
        }

        // 从未读列表中移除
        unreadNotifications.value = unreadNotifications.value.filter(n => n.id !== notificationId)
        unreadCount.value = Math.max(0, unreadCount.value - 1)

        return { success: true }
      } else
      {
        throw new Error(response.message || '标记通知已读失败')
      }
    } catch (error)
    {
      console.error('标记通知已读失败:', error)
      ElMessage.error('操作失败: ' + error.message)
      return { success: false, message: error.message }
    }
  }

  // 标记所有通知为已读
  const markAllNotificationsAsRead = async () =>
  {
    try
    {
      const response = await put('/notifications/read-all')
      if (response.code === 200)
      {
        // 更新本地状态
        notifications.value.forEach(notification =>
        {
          if (notification.status === 'UNREAD')
          {
            notification.status = 'READ'
            notification.readAt = new Date().toISOString()
          }
        })

        unreadNotifications.value = []
        unreadCount.value = 0

        ElMessage.success('所有通知已标记为已读')
        return { success: true, data: response.data }
      } else
      {
        throw new Error(response.message || '标记所有通知已读失败')
      }
    } catch (error)
    {
      console.error('标记所有通知已读失败:', error)
      ElMessage.error('操作失败: ' + error.message)
      return { success: false, message: error.message }
    }
  }

  // 轮询检查新通知
  const checkForNewNotifications = async () =>
  {
    try
    {
      const result = await fetchNotificationStats()
      if (result.success)
      {
        return result.data
      }
    } catch (error)
    {
      console.warn('检查新通知失败:', error)
    }
    return null
  }

  // 格式化通知类型显示
  const getNotificationTypeText = (type) =>
  {
    const typeMap = {
      'AVATAR_APPROVED': '头像审核通过',
      'AVATAR_REJECTED': '头像审核拒绝',
      'SYSTEM_NOTICE': '系统通知',
      'SECURITY_ALERT': '安全提醒'
    }
    return typeMap[type] || type
  }

  // 获取通知类型图标
  const getNotificationIcon = (type) =>
  {
    const iconMap = {
      'AVATAR_APPROVED': 'success',
      'AVATAR_REJECTED': 'warning',
      'SYSTEM_NOTICE': 'info',
      'SECURITY_ALERT': 'error'
    }
    return iconMap[type] || 'info'
  }

  // 重置状态
  const reset = () =>
  {
    notifications.value = []
    unreadNotifications.value = []
    unreadCount.value = 0
    loading.value = false
  }

  return {
    // 状态
    notifications,
    unreadNotifications,
    unreadCount,
    loading,

    // 计算属性
    hasUnreadNotifications,

    // 方法
    fetchNotificationStats,
    fetchNotifications,
    fetchUnreadNotifications,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    checkForNewNotifications,
    getNotificationTypeText,
    getNotificationIcon,
    reset
  }
})
